package com.zhang.authority.config.handler;

import com.alibaba.fastjson.JSON;
import com.zhang.authority.model.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

   @Override
   public void commence(HttpServletRequest request,
                        HttpServletResponse response,
                        AuthenticationException authException) throws IOException {

      log.error("401 无法访问：{}",authException.getMessage());
      response.setContentType("application/json;charset=utf-8");
      ResponseVO<Object> kingHoodResponseVO = ResponseVO.fail(HttpServletResponse.SC_UNAUTHORIZED, "请重新登录");
      response.getWriter().println(JSON.toJSONString(kingHoodResponseVO));
      response.getWriter().flush();
   }
}
